package com.imooc.dianping.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.imooc.dianping.common.BusinessException;
import com.imooc.dianping.common.CommonUtil;
import com.imooc.dianping.common.EmBusinessError;
import com.imooc.dianping.dao.UserMapper;
import com.imooc.dianping.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.NoSuchAlgorithmException;

@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    @Autowired
    private UserMapper userMapper;

    @Transactional(rollbackFor = Exception.class)
    public User register(User user) throws NoSuchAlgorithmException {
        if (userMapper.selectByTelphone(user.getTelphone()) != null) {
            throw new BusinessException(EmBusinessError.REGISTER_DUP_FAIL);
        }
        user.setPassword(CommonUtil.encodeByMd5(user.getPassword()));
        userMapper.insert(user);
        return user;
    }


    @Transactional(readOnly = true)
    public User login(String telphone, String password) throws NoSuchAlgorithmException {
        User user = userMapper.selectByTelphone(telphone);
        if (user == null || !user.getPassword().equals(CommonUtil.encodeByMd5(password))) {
            throw new BusinessException(EmBusinessError.LOGIN_ERROR);
        }

        return user;
    }
}
